package csm.sql.pool;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import csm.sql.ConnectionFactory;
import csm.sql.DBConfig;
import csm.sql.SmartConnection;

/**
 * 
 * @author seungmun
 * @since 2006.1.18.
 * @version
 * @see
 */
public class JNDIConnectionPool extends ConnectionFactory
{
	private DataSource ds;
	private ConnectionFactory util;
	private String dbms;

	@Override
	protected void createConnectionPool() throws SQLException
	{
		Context initContext;
		try
		{
			String dataSourceName = "";
			
			DBConfig dbc = DBConfig.getDBConfig(this.connectionName);
			dataSourceName = dbc.getSettings("dataSourceName");
			
			initContext = new InitialContext();
			Context envContext = (Context) initContext.lookup("java:/comp/env");
			ds = (DataSource) envContext.lookup(dataSourceName);
		}
		catch (NamingException e)
		{
			throw new SQLException(String.format("error raised in JNDIConnectionPool.getConnection().(%1$s)", e.getMessage()), e);
		}
		finally
		{
		}
	}

	@Override
	public Connection getConnection() throws SQLException
	{		
		if( ds == null)
			createConnectionPool();
		
		Connection cn = ds.getConnection();
		
		return new SmartConnection(cn);
	}

	@Override
	public void closeConnectionPool() throws SQLException
	{
		if( ds != null)
			ds = null;
	}

	@Override
	public String createMaxQuery(String table, String column, String where)
	{
		if (util == null)
		{
			try
			{
				if (dbms == null)
				{
					DBConfig dbc = DBConfig.getDBConfig(this.connectionName);
					dbms = dbc.getSettings("connection.dbms");
				}
				util = (ConnectionFactory) Class.forName(String.format("csm.sql.pools.%1$sConnectionPool", dbms)).newInstance();
			}
			catch (Exception e)
			{
				System.out.println(String.format("csm.sql.pools.%1$sConnectionPool doesn't exists!", dbms));
				e.printStackTrace();
				return super.createMaxQuery(table, column, where);
			}
		}

		return util.createMaxQuery(table, column, where);
	}

}
